package com.qf.service.impl;/*
 *徐韬
 *2021/10/25
 *20:41
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.cache.dritywordCache;
import com.qf.cache.paramsCache;
import com.qf.constons.resultCode;
import com.qf.events.UpdateDirtywordevents;
import com.qf.exceptions.MybaseExecption;
import com.qf.exceptions.updateException;
import com.qf.mapper.dirtywordMapper;
import com.qf.pojo.MyAuthUser;
import com.qf.pojo.Params;
import com.qf.pojo.TAdminUser;
import com.qf.pojo.TDirtyword;
import com.qf.service.dirtywordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.naming.Context;
import javax.servlet.http.HttpServletRequest;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class dirtywordServiceimpl implements dirtywordService {
    private dritywordCache dirtywordCache;
   private dirtywordMapper dirtywordMapper;
   private paramsCache paramsCache;
@Autowired
    public void setParamsCache(com.qf.cache.paramsCache paramsCache) {
        this.paramsCache = paramsCache;
    }

    private ApplicationContext context;
@Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setDirtywordCache(dritywordCache dirtywordCache) {
        this.dirtywordCache = dirtywordCache;
    }

    @Autowired
    public void setDirtywordMapper(com.qf.mapper.dirtywordMapper dirtywordMapper) {
        this.dirtywordMapper = dirtywordMapper;
    }

    @Override
    public TDirtyword showDirtywordById(Long id) {
     if(ObjectUtils.isEmpty(id) || id <= 0){
         //id不符合传递的要求
         throw new MybaseExecption("传递的参数（主键不合法）", resultCode.PK_NOT_ALLOW);

     }
        return dirtywordCache.getById(id);
    }

    @Override
    public void addDirtyword(TDirtyword tDirtyword) {
        if(ObjectUtils.isEmpty(tDirtyword)){
            throw new MybaseExecption("传入的参数为空", resultCode.PK_NOT_ALLOW);
        }
        dirtywordMapper.insert(tDirtyword);
        context.publishEvent(new UpdateDirtywordevents());

    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<TDirtyword> showAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
//        List<TDirtyword> tDirtywords = dirtywordMapper.selectAll();
//        PageInfo<TDirtyword> pageInfo = new PageInfo<>(tDirtywords);
        List<TDirtyword> dirtywordList = dirtywordCache.getfinlAll();
//        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();//在service中获取一个session
//        TAdminUser user = (TAdminUser) ((ServletRequestAttributes) requestAttributes).getRequest().getSession().getAttribute("user");//将用户信息取出
        MyAuthUser authUser = (MyAuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<TDirtyword> dirtywords = dirtywordList.stream().filter(dir -> {
            return dir.getOwntype() == 1 || dir.getCreater() == authUser.getId() || authUser.getType() == 1;
        }).collect(Collectors.toList());
        List<TDirtyword> subList = dirtywords.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        PageInfo<TDirtyword> pageInfo = new PageInfo<>(subList);
        pageInfo.setTotal(dirtywords.size());

        return pageInfo;
}

    @Override
    public void updateDirtywordById(TDirtyword tDirtyword) {
        TDirtyword tDirtyword1 = dirtywordMapper.selectById(tDirtyword.getId());
        if(tDirtyword.getOwntype() != 1 && tDirtyword.getCreater() != tDirtyword1.getCreater()){
            throw new updateException("您无权修改该用户的信息",resultCode.NO_ROOT);

        }
        dirtywordMapper.updateDirtywordById(tDirtyword);
        context.publishEvent(new UpdateDirtywordevents());

    }

    @Override
    public void deleteDirtywordByids(List<Integer> ids) {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();//在service中获取一个session
        TAdminUser user = (TAdminUser) ((ServletRequestAttributes) requestAttributes).getRequest().getSession().getAttribute("user");//将用户信息取出
        if(user.getType() ==1){
            //是管理员可以删除所有
            dirtywordMapper.deletedritywordByids(ids);
            return;
        }
        dirtywordMapper.deletedirtywordByidsandcreater(ids,user.getId());
        context.publishEvent(new UpdateDirtywordevents());

    }

    @Override
public List<TDirtyword> showAllByparams(TDirtyword tDirtyword) {
    Class<? extends TDirtyword> tDirtywordClass = tDirtyword.getClass();
    TDirtyword  instance = null;
    try {
        instance = tDirtywordClass.newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    Params dirtyword = paramsCache.getById("dirtyword");
    List<String> params = new ArrayList<>();
    String param1 = dirtyword.getParam1();
    String param2 = dirtyword.getParam2();
    String param3 = dirtyword.getParam3();
    if(param1 != null){
        params.add(param1);
    }
    if(param2 != null){
        params.add(param2);
    }
    if(param3 != null){
        params.add(param3);
    }
    TDirtyword instance1 = instance;
    params.forEach(param->{
        try {
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(param, tDirtywordClass);
            Method writeMethod = propertyDescriptor.getWriteMethod();
            Method readMethod = propertyDescriptor.getReadMethod();
            writeMethod.invoke(instance1,readMethod.invoke(tDirtyword));
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    });
    List<TDirtyword> dirtywords = dirtywordMapper.showAllByparams(instance1);
    return dirtywords;


}
}
